<template>
  <!-- 生成报价弹框 -->
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogVisible"
    :beforeClose="handleClose"
    width="500px"
  >
    <div>
      <el-form
        size="mini"
        :model="sendForm"
        label-width="130px"
        ref="sendForm"
        :rules="rules"
      >
        <el-form-item label="报价日期：">
          {{ date }}
        </el-form-item>
        <el-form-item label="供应商：" prop="fromCompany">
          <span v-if="title=='编辑报价'">{{ sendForm.fromCompany }}</span>
          <el-select v-else v-model="sendForm.fromCompany" @change="handleWarehouse" filterable clearable>
            <el-option
              v-for="item in fromCompanyList"
              :key="item.fromCompanyId"
              :label="item.fromCompanyName"
              :value="item.fromCompanyName"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库：" prop="warehouseName">
          <span v-if="title=='编辑报价'">{{ sendForm.warehouseName }}</span>
          <el-select
            v-else
            v-model="sendForm.warehouseName"
            filterable
            clearable
            @change="handleSendArea"
          >
            <el-option
              v-for="item in warehouseLists"
              :label="item.warehouseName"
              :value="item.warehouseName"
              :key="item.warehouseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货地区：" prop="sendAreaId">
          <el-cascader
            ref="diQuIds"
            filterable
            clearable
            v-model="sendForm.sendAreaId"
            :props="{
              value: 'areaId',
              label: 'areaName',
              children: 'children',
            }"
            :options="options"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="发货日期：" prop="sendDate">
          <el-date-picker
            style="width: 130px"
            value-format="yyyy-MM-dd"
            v-model="sendForm.sendDate"
            :picker-options="pickerOptions1"
            type="date"
            placeholder="选择日期时间："
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货方式：" prop="sendTypes">
          <el-select
            v-model="sendForm.sendTypes"
            style="width: 100px"
            @change="changeSendTypes"
          >
            <el-option label="送到" value="送到"></el-option>
            <el-option label="自提" value="自提"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购底价：" prop="purchasePrice">
          <el-input style="width:150px" v-model="sendForm.purchasePrice" clearable></el-input>
          <div v-if="
          (categoryMinPrice > 0 || categoryMaxPrice > 0)
          && (sendForm.purchasePrice < categoryMinPrice || sendForm.purchasePrice > categoryMaxPrice)"
          style="color: red;font-size:10px;">
            未在产品线参考价格范围内
          </div>
        </el-form-item>
        <el-form-item label="采购成本价：" prop="costPrice">
          <el-input
            style="width: 150px"
            v-model="sendForm.costPrice"
            clearable
          ></el-input>
          <div
            v-if="sendForm.purchasePrice > 0 && sendForm.costPrice > 0"
            style="color: red;font-size:12px;">
            采购吨毛利：{{ sendForm.purchasePrice | fifterNumber(sendForm.costPrice) }}
          </div>
        </el-form-item>
        <el-form-item label="线上平台价：" prop="onlinePrice" v-if="sendForm.sendTypes=='自提'">
          <el-input
            style="width: 150px"
            v-model="sendForm.onlinePrice"
            clearable
          ></el-input>
          <div
            style="color: red;font-size:12px;">
            请注意最低毛利为{{ minProfit }}元/吨
          </div>
        </el-form-item>
        <el-form-item label="有效小时数：" v-if="sendForm.onlinePrice>0" prop="validHours">
          <el-input
            style="width: 150px"
            v-model="sendForm.validHours"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="可售库存量(吨)：" prop="stockNum">
          <el-input
            v-model="sendForm.stockNum"
            style="width: 100px"
            :max="66"
            clearable
          ></el-input>
        </el-form-item>
        <!-- 起订量(吨) -->
        <el-form-item label="起订量(吨)：" prop="buyMinNum">
          <el-input
            v-model="sendForm.buyMinNum"
            style="width: 100px"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="价格类型：" prop="priceType">
          <el-select v-model="sendForm.priceType" style="width: 100px">
            <el-option label="滞销" value="滞销"></el-option>
            <el-option label="平稳" value="平稳"></el-option>
            <el-option label="紧俏" value="紧俏"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发货类型：" prop="deliveryType">
          <el-select v-model="sendForm.deliveryType" style="width:100px;">
            <el-option :disabled="deliveryData=='自提'" label="采购发货" value="采购发货" ></el-option>
            <el-option label="客户自提" value="客户自提"></el-option>
            <el-option label="公司发货" value="公司发货"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input
            v-model="sendForm.priceRemark"
            style="width: 150px"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="btnLoading"
        >确认</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import {
  goodsPricePublish,
  getFromCompanyList,
  warehouseList,
  getAreaList,
} from "@/api/allInLine/inquiry";
import { mapGetters } from "vuex";
import { Message } from "element-ui";

const defaultSendForm = {
  goodsDetailId: "", //规格商品ID
  sendAreaId: "", //发货区域ID(修改时，非必填)
  fromCompany: "", //供货方
  warehouseName: "", //发货仓库
  stockNum: "", //库存
  payTypes: "", //结算方式(修改时，非必填)
  purchasePrice: "", //采购底价
  costPrice: "",//采购成本价
  onlinePrice: "",//线上平台价
  validHours:"",//有效小时数
  sendDate: "", //发货日期
  sendTypes: "", //发货方式(修改时，非必填)
  buyMinNum: "", //起订量(修改时，非必填)
  priceType: "", //价格类型(滞销、紧俏、平稳)(修改时，非必填)
  priceRemark: "", //备注(修改时，非必填)
  deliveryType: "", //发货类型(公司发货、采购发货、客户自提)
  priceTime: "",
};
export default {
  name: "addTempOffer",
  data() {
    const validatePrice= (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('价格不能小于0元'))
      }
      callback()
    };
    const validateStockNum = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('数量不能小于0吨'))
      }
      callback()
    };
    const validateHours = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('有效小时数不得小于0小时'))
      }
      callback()
    };
    return {
      title:'',
      dialogVisible: false,
      btnLoading: false,
      date: "",
      sendForm: JSON.parse(JSON.stringify(defaultSendForm)),
      minProfit:'',//最低毛利
      rules: {
        purchasePrice: [
          { required: true, message: "请输入采购底价", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        costPrice: [
          { required: true, message: "请输入采购成本价", trigger: "blur" },
          {validator:validatePrice,trigger: "blur"}
        ],
        onlinePrice: [
          {validator:validatePrice,trigger: "blur"}
        ],
        validHours: [
          { required: true, message: "请输入有效小时数", trigger: "blur" },
          {validator:validateHours,trigger: "blur"}
        ],
        sendDate: [
          { required: true, message: "请选择发货日期", trigger: "change" },
        ],
        stockNum: [
          { required: true, message: "请输入可售库存量", trigger: "blur" },
          { validator:validateStockNum,trigger: "blur"}
        ],
        buyMinNum: [
          { validator:validateStockNum,trigger: "blur"}
        ],
        fromCompany: [
          { required: true, message: "请选择供货商", trigger: "change" },
        ],
        warehouseName: [
          { required: true, message: "请选择仓库", trigger: "change" },
        ],
        sendTypes: [
          { required: true, message: "请选择发货方式", trigger: "change" },
        ],
        deliveryType: [
          { required: true, message: "请选择发货类型", trigger: "change" },
        ],
        priceType: [
          { required: true, message: "请选择价格类型", trigger: "change" },
        ],
        sendAreaId: [
          { required: true, message: "发货区域必填", trigger: "change" },
        ],
      },
      options: [],
      diQuIds: [],
      deliveryData: "",
      fromCompanyList: [],
      warehouseLists: [],
      pickerOptions1: {
        disabledDate(time) {
            return time.getTime() < Date.now()  - 8.64e7;
        },
      },
      categoryMinPrice: "",
      categoryMaxPrice: ""
    }
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  components: {},
  created() {},
  filters: {
    fifterNumber(val1, val2) {
      let newval1 = val1 ? val1 : 0;
      let newval2 = val2 ? val2 : 0;
      return (newval1 - newval2).toFixed(2)
    }
  },
  methods: {
    //显示
    showPop(item, type) {
      this.dialogVisible = true;
      this.fromCompanysList();
      this.getAddressListData();
      const today = new Date();
      const year = today.getFullYear();
      const month = ('0' + (today.getMonth() + 1)).slice(-2); // 加1是因为月份从0开始计数，slice(-2)用于保留两位数
      const day = ('0' + today.getDate()).slice(-2);
      this.date = `${year}-${month}-${day}`;
      // 获取最低毛利
      this.minProfit = item.minProfit;
      // 获取供应商列表
      if (item.hasOwnProperty('fromCompany')) {
        warehouseList({ fromCompany: item.fromCompany }).then(res => {
          this.warehouseLists = res.list
        })
        this.changeSendTypes(this.sendForm.sendTypes)

        for (let key in defaultSendForm) {
          if(type == 'edit'){
            this.sendForm[key]=item[key]?item[key]:defaultSendForm[key]
          }else{
            this.sendForm[key]=defaultSendForm[key]
          }
        }
        if(type == 'edit'){
          this.sendForm.sendAreaId = item.provinceId ? [item.provinceId, item.cityId, item.areaId] : '';
        }else{
          this.sendForm.sendAreaId = '';
        }
        this.sendForm.goodsDetailId = item.goodsDetailId ? item.goodsDetailId : '';
        this.sendForm.stockNum = item.goodsStock ? item.goodsStock : '';
        this.sendForm.buyMinNum = item.buyMinNum ? item.buyMinNum : '';



      }
       if (type == 'edit') {
        this.title = '编辑报价'
        this.sendForm.priceId = item.priceId
      } else {
        this.title = '生成报价'
      }
    },
    //关闭
    handleClose() {
      this.dialogVisible = false;
      this.$refs.sendForm.resetFields();
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
    },

    //确认
    handleConfirm() {
      this.$refs.sendForm.validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.sendForm));
          data.sendAreaId = data.sendAreaId
            ? data.sendAreaId[data.sendAreaId.length - 1]
            : "";
          this.btnLoading = true;
          goodsPricePublish({ goodsList: [data] })
            .then((res) => {
              if (res) {
                Message.success("生成报价成功");
                if (this.sendForm.purchasePrice - this.sendForm.costPrice <= -200) {
                  this.$alert('您的报价中存在毛利过低', '提示', {
                    confirmButtonText: '关闭',
                  });
                }
                Message.success("生成报价成功");
                this.btnLoading = false;
                this.dialogVisible = false;
                this.$refs.sendForm.resetFields();
                this.$emit("update");
                this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
              }
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    // 发货公司列表
    fromCompanysList() {
      getFromCompanyList().then((res) => {
        this.fromCompanyList = res;
      });
    },

    //获取省市区列表
    getAddressListData() {
      getAreaList().then((res) => {
        this.options = res;
      });
    },

    // 更改仓库触发
    handleSendArea(val) {
      this.sendForm.sendAreaId = [];
      const data = this.warehouseLists.filter((item) => {
        return item.warehouseName == val;
      });
      if (data.length > 0) {
        this.sendForm.sendAreaId = [
          data[0].provinceId,
          data[0].cityId,
          data[0].areaId,
        ];
      }
    },

    handleWarehouse(val) {
      this.sendForm.warehouseName = "";
      warehouseList({ fromCompany: val }).then((res) => {
        this.warehouseLists = res.list;
      });
    },

    // 发货方式更改
    changeSendTypes(val) {
      this.deliveryData = val;
      this.sendForm.onlinePrice = '';
      this.sendForm.validHours = '';
      if (val == "自提") {
        this.sendForm.deliveryType = "";
      } else if (val == "送到") {
        this.sendForm.deliveryType = "采购发货";
      }
    },
  },
};
</script>

<style  lang="scss">
</style>
